import { Component, OnInit, ViewChild, TemplateRef } from '@angular/core'
import { Router, ActivatedRoute } from '@angular/router'
import { NzMessageService } from 'ng-zorro-antd'
import { STColumn } from '@delon/abc'
import { ACLService } from '@delon/acl'
import { SettingsService } from '@delon/theme'

import { I18NService } from '@core'
import { MerchantService } from '../merchant.service'
import { ListBaseClass } from '@shared/classes/ListBaseClass'
import { Merchant, IMerchantQueryParams } from '@shared/interfaces/merchant'
import { ISearchSchema } from '@shared/interfaces/search'
import { ESearchType, EColumnType } from '@shared/enums'
import { AAMSFilterInit } from '@shared/interfaces/aams'
import { ModalService } from '@shared/services/modal.service'

@Component({
  selector: 'app-merchant-list',
  templateUrl: './list.component.html',
  styleUrls: ['../../../shared/styles/table.less'],
})
export class MerchantListComponent extends ListBaseClass<Merchant, IMerchantQueryParams>
  implements OnInit, AAMSFilterInit {
  @ViewChild('tplAcquirer') tplAcquirer: TemplateRef<void>
  @ViewChild('tplGroup') tplGroup: TemplateRef<void>
  @ViewChild('tplMerchant') tplMerchant: TemplateRef<void>

  searchSchema: ISearchSchema[] = []
  customSchema: ISearchSchema[] = []

  data: Merchant[] = []

  columns: STColumn[] = []

  constructor(
    public msg: NzMessageService,
    public i18n: I18NService,
    public router: Router,
    public route: ActivatedRoute,
    private merchantService: MerchantService,
    public settings: SettingsService,
    private modalService: ModalService,
    public aclService: ACLService,
  ) {
    super(msg, i18n, route, router, settings)
  }

  ngOnInit(): void {
    this.initColumns()
    this.parseParams().subscribe(() => {
      this.queryTableDataWithParams()
    })
    this.searchSchema = this.createSearchSchema()
    this.initialAAMSFilter()
  }

  initialAAMSFilter() {
    this.initAcquirer()
    this.initAgent()
    this.initMerchant()
  }

  goNew(): void {
    this.router.navigate(['../new'], { relativeTo: this.route })
  }

  queryTableDataWithParams(): void {
    this.loading = true
    this.merchantService.getList(this.params).subscribe(this.renderList.bind(this), this.getListError.bind(this))
  }

  viewDetail(data): void {
    const { intMerCode } = data.common
    this.router.navigate([`../${intMerCode}`], { relativeTo: this.route })
  }

  freezeDialog(record: Merchant): void {
    const { merName } = record.common
    const msg = this.trans('GENERAL.NOTIFICATION.MERCHANT_FREEZE_CONFIRM', { merName })
    this.modalService.freezeAndUnFreeze(msg).subscribe(isOK => {
      if (!isOK) return
      this.freeze(record)
    })
  }

  unfreezeDialog(record: Merchant): void {
    const { merName } = record.common
    const msg = this.trans('GENERAL.NOTIFICATION.MERCHANT_UNFREEZE_CONFIRM', { merName })
    this.modalService.freezeAndUnFreeze(msg).subscribe(isOK => {
      if (!isOK) return
      this.unfreeze(record)
    })
  }

  freeze(record: Merchant): void {
    const { intMerCode } = record.common
    this.merchantService.freeze(intMerCode).subscribe(
      success => {
        this.msg.success(this.trans('GENERAL.NOTIFICATION.FREEZE_SUCCESS'))
        this.st.reload()
      },
      err => {
        this.msg.error(this.trans('GENERAL.NOTIFICATION.FREEZE_FAIL'))
      },
    )
  }

  unfreeze(record: Merchant): void {
    const { intMerCode } = record.common
    this.merchantService.unfreeze(intMerCode).subscribe(
      success => {
        this.msg.success(this.trans('GENERAL.NOTIFICATION.UNFREEZE_SUCCESS'))
        this.st.reload()
      },
      err => {
        this.msg.error(this.trans('GENERAL.NOTIFICATION.UNFREEZE_FAIL'))
      },
    )
  }

  private initColumns() {
    const canLock = this.aclService.canAbility('api.put.camel.merchant.one.freeze')
    const canUnlock = this.aclService.canAbility('api.put.camel.merchant.one.unfreeze')
    this.columns = [
      {
        type: 'link',
        title: '商户编号',
        i18n: 'GENERAL.MERCHANT.NUM',
        index: 'common.merNum',
        className: 'text-center p-xs',
        width: '120px',
        fixed: 'left',
        click: this.viewDetail.bind(this),
      },
      {
        title: '商户名称',
        i18n: 'GENERAL.MERCHANT.NAME',
        index: 'common.merName',
        width: '150px',
        className: 'text-left',
      },
      {
        title: '商户英文名称',
        i18n: 'GENERAL.MERCHANT.NAME_EN',
        index: 'common.merNameEN',
        width: '150px',
        className: 'text-left',
      },
      {
        title: '集团名称',
        i18n: 'GENERAL.AGENT.NAME',
        index: 'common.agentName',
        width: '150px',
        className: 'text-left',
      },
      {
        title: '创建时间',
        i18n: 'GENERAL.INFO.CREATED_AT',
        index: 'createdAt',
        className: 'text-center',
        type: EColumnType.Date,
        dateFormat: 'YYYY-MM-DD HH:mm',
        width: '120px',
      },
      {
        title: '操作',
        i18n: 'GENERAL.INFO.OPERATION',
        width: '100px',
        fixed: 'right',
        className: 'text-center p-xs',
        iif: () => canLock || canUnlock,
        buttons: [
          {
            text: '',
            icon: {
              iconfont: 'icon-lock-twotone',
              type: 'iconfont',
            },
            click: this.freezeDialog.bind(this),
            iif: record => canLock && record.common.status === 'normal',
          },
          {
            text: '',
            icon: {
              iconfont: 'icon-unlock-circle',
              type: 'iconfont',
            },
            click: this.unfreezeDialog.bind(this),
            iif: record => canUnlock && record.common.status === 'freeze',
          },
        ],
      },
    ]
  }

  private createSearchSchema(): ISearchSchema[] {
    return [
      {
        label: 'GENERAL.INFO.CREATED_AT',
        labelI18n: 'GENERAL.INFO.CREATED_AT',
        index: 'createTime',
        type: ESearchType.dateRange,
        value: [],
      },
      {
        label: 'GENERAL.BIZ_LEVEL.INSTITUTION',
        labelI18n: 'GENERAL.BIZ_LEVEL.INSTITUTION',
        index: 'insCode',
        component: this.tplAcquirer,
        customFunc: () => this.selectedAcquirer && this.selectedAcquirer.code,
      },
      {
        label: 'GENERAL.BIZ_LEVEL.AGENT',
        labelI18n: 'GENERAL.BIZ_LEVEL.AGENT',
        index: 'agentCode',
        component: this.tplGroup,
        customFunc: () => this.selectedGroup && this.selectedGroup.code,
      },
      {
        label: 'GENERAL.BIZ_LEVEL.MERCHANT',
        labelI18n: 'GENERAL.BIZ_LEVEL.MERCHANT',
        index: 'intMerCode',
        component: this.tplMerchant,
        customFunc: () => this.selectedMerchant && this.selectedMerchant.code,
      },
      {
        label: 'GENERAL.INFO.STATUS',
        labelI18n: 'GENERAL.INFO.STATUS',
        index: 'status',
        type: ESearchType.selection,
        options: [
          { label: this.trans('GENERAL.STATUS.NORMAL'), value: 'normal' },
          { label: this.trans('GENERAL.STATUS.FREEZE'), value: 'freeze' },
        ],
      },
    ]
  }
}
